import { storeToRefs } from 'pinia';
import { computed, getCurrentInstance, nextTick, ref, watch } from 'vue';
import { useAppStore } from '@/store/appStore';
import { getRect } from '@/utils/dom.utils';

export function useScrollViewHelper(gutter = 20) {
  const $scrollContainer = 'scroll-container';
  const $scrollContainerSelector = `.${$scrollContainer}`;

  const $scrollCard = 'scroll-card';
  const $scrollCardSelector = `.${$scrollCard}`;

  const instance = getCurrentInstance().proxy;

  const { scale: autoFitScale } = storeToRefs(useAppStore());

  // 最大可滚动距离（contentWidth - containerWidth）
  const maxScrollX = ref(0);
  // 当前滚动距离
  const scrollLeft = ref(0);
  // 百分比 0 ~ 100
  const percentage = ref(0);

  const scrollAnimation = ref(false);

  const canLeftScroll = computed(() => {
    return scrollLeft.value > 0;
  });

  const canRightScroll = computed(() => {
    return scrollLeft.value < maxScrollX.value - 1;
  });

  function updatePercentage() {
    const max = maxScrollX.value;
    if (!max || max <= 0) {
      percentage.value = 0;
      return;
    }
    const clamped = Math.min(scrollLeft.value, max);
    let p = (clamped / max) * 100;
    if (!Number.isFinite(p))
      p = 0;
    percentage.value = Math.min(100, Math.max(0, Number(p.toFixed(2))));
  }

  function onScroll(e) {
    const rawLeft = e?.detail?.scrollLeft || 0;
    scrollLeft.value = rawLeft;

    updatePercentage();
  }

  async function getScrollView(selector = $scrollContainerSelector) {
    await nextTick();

    uni.createSelectorQuery()
      .in(instance)
      .select(selector)
      .fields({ size: true, scrollOffset: true }, () => { })
      .exec(resArr => {
        const info = resArr && resArr[0] ? resArr[0] : null;
        if (!info) {
          maxScrollX.value = 0;
          isOverFlow.value = false;
          return;
        }
        const containerWidth = info.width / autoFitScale.value || 0;
        const contentWidth = info.scrollWidth;

        // 判断子内容是否超出父节点容器 允许2px 的误差
        isOverFlow.value = contentWidth - 2 > containerWidth;

        const rawMax = Math.max(0, contentWidth - containerWidth);
        maxScrollX.value = rawMax;
        updatePercentage();
      });
  }

  async function handleScroll(direction: 'left' | 'right') {
    // 卡片宽度
    const { width } = await getRect($scrollCardSelector, false, instance);

    const offset = width / autoFitScale.value + 20;

    if (direction === 'left' && canLeftScroll.value) {
      scrollLeft.value -= offset;
    }
    else if (direction === 'right' && canRightScroll.value) {
      scrollLeft.value += offset;
    }
    updatePercentage();
  }

  async function scrollToIndex(index: number) {
    // 卡片宽度
    const { width: originCardWidth } = await getRect($scrollCardSelector, false, instance);

    // 容器宽度
    const { width: originContainerWidth } = await getRect($scrollContainerSelector, false, instance);

    const cardWidth = originCardWidth / autoFitScale.value;
    const containerWidth = originContainerWidth / autoFitScale.value;

    // 计算选中卡片的左侧位置
    const cardOffsetLeft = index * (cardWidth + gutter);

    const cardCenter = cardOffsetLeft + cardWidth / 2;

    scrollAnimation.value = true;

    // 滚动到指定位置
    scrollLeft.value = cardCenter - containerWidth / 2;

    // 确保滚动生效
    nextTick(() => {
    // 更新进度条
      updatePercentage();
      scrollAnimation.value = false;
    });
  }

  // isOverFlow 子内容是否超出父节点容器
  const isOverFlow = ref(false);

  watch(autoFitScale, () => {
    getScrollView();
  }, { immediate: true });

  return {
    $scrollContainer,
    $scrollCard,

    isOverFlow,

    scrollAnimation,
    percentage,
    scrollLeft,
    canLeftScroll,
    canRightScroll,
    updatePercentage,
    onScroll,
    getScrollView,
    handleScroll,
    scrollToIndex
  };
}
